package leetcode.editor.cn;

//从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。 
//
// 
//
// 例如: 
//给定二叉树: [3,9,20,null,null,15,7], 
//
//     3
//   / \
//  9  20
//    /  \
//   15   7
// 
//
// 返回其层次遍历结果： 
//
// [
//  [3],
//  [9,20],
//  [15,7]
//]
// 
//
// 
//
// 提示： 
//
// 
// 节点总数 <= 1000 
// 
//
// 注意：本题与主站 102 题相同：https://leetcode-cn.com/problems/binary-tree-level-order-
//traversal/ 
// Related Topics 树 广度优先搜索 二叉树 👍 162 👎 0

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class CongShangDaoXiaDaYinErChaShuIiLcof{
	public static void main(String[] args) {
		Solution solution = new CongShangDaoXiaDaYinErChaShuIiLcof().new Solution();
		CongShangDaoXiaDaYinErChaShuIiLcof.TreeNode root = new CongShangDaoXiaDaYinErChaShuIiLcof.TreeNode(3);
		root.left = new CongShangDaoXiaDaYinErChaShuIiLcof.TreeNode(9);
		root.right = new CongShangDaoXiaDaYinErChaShuIiLcof.TreeNode(20);
		root.right.left = new CongShangDaoXiaDaYinErChaShuIiLcof.TreeNode(15);
		root.right.right = new CongShangDaoXiaDaYinErChaShuIiLcof.TreeNode(7);
		List<List<Integer>> res = new ArrayList<>();
		res = new CongShangDaoXiaDaYinErChaShuIiLcof().new Solution().levelOrder(root);
		System.out.println(res.toString());
	}
//leetcode submit region begin(Prohibit modification and deletion)

public static class TreeNode {
  int val;
  TreeNode left;
  TreeNode right;
  TreeNode(int x) { val = x; }
}

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
		List<List<Integer>> temp = new ArrayList<>();
		if (root == null) return temp;
		Queue<TreeNode> queue = new LinkedList<>();
		queue.offer(root);
		while (!queue.isEmpty()) {
			List<Integer> list = new ArrayList<>();
			// 注意在for循环中queue.size()会变化,应该定义在初始化中，不能使用i < queue.size()

			for (int i = queue.size(); i > 0; i--) {
				TreeNode node = queue.poll();
				list.add(node.val);
				if (node.left != null) queue.offer(node.left);
				if (node.right != null) queue.offer(node.right);
			}
			temp.add(list);
		}
		return temp;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}
